package com.budayi.filter;

import com.budayi.common.CommonConstants;
import com.budayi.common.cache.RedisCacheChannel;
import com.budayi.common.utils.JsonResult;
import com.budayi.common.utils.ObjectUtils;
import com.budayi.common.utils.ReponseUtil;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author LIBOFEI
 * @ClassName AdminLoginAuthFilter
 * @description 后台登录验证权限
 * @date 2021/4/30 09:52
 * @Version 1.0
 **/
public class AdminLoginAuthFilter implements GatewayFilter, Ordered {

    private RedisCacheChannel redisCacheChannel;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入了后台登录验证权限过滤");
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().pathWithinApplication().value();
        if(path.indexOf("login") > -1){
            return chain.filter(exchange);
        }
        HttpCookie cookie = request.getCookies().getFirst(CommonConstants.ADMIN_COOKIE_ID);
        if(ObjectUtils.isNull(cookie)){
            ReponseUtil.reponse(exchange,JsonResult.CODE_ADMIN_LOGIN,"未登录");
        }
        String uuid = cookie.getValue();
        ApplicationContext context = exchange.getApplicationContext();
        if(context != null && context.getBean("redisCacheChannel") != null && redisCacheChannel == null){
            redisCacheChannel = (RedisCacheChannel)context.getBean("redisCacheChannel");
        }
        Object o = redisCacheChannel.get(uuid);
        if(ObjectUtils.isNull(o)){
            ReponseUtil.reponse(exchange,JsonResult.CODE_ADMIN_LOGIN,"未登录");
        }
        System.out.println("登录信息为："  + o);
        return chain.filter(exchange);
    }



    @Override
    public int getOrder() {
        return 2;
    }
}
